package com.woniuxy.dudugua.exception;

import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

public class GlobleException implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) {
        e.printStackTrace();
        FastJsonJsonView view = new FastJsonJsonView();
        response.setStatus(500);
        HashMap<String,Object> map = new HashMap<String,Object>();
        map.put("code",500);
        //判断异常类型
        if(e instanceof UnknowAccountException) {
            map.put("message", "用户名不存在");
        }else if(e instanceof IncorrectCredentialsException) {
            map.put("message", "密码错误");
        }else {
            map.put("message", "服务器内部异常");
        }
        if(e instanceof ParamException) {
            ModelAndView mav = new ModelAndView("/errors");
            mav.addObject("errors", "非法参数");
            return mav;
        }
        view.setAttributesMap(map);
        return new ModelAndView(view);
    }
}
